package com.ycx.furns.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class JDBCUtilsByDruid {
    static DataSource dataSource;
    static Connection connection;
    static ThreadLocal<Connection> threadLocal = new ThreadLocal<>();
    static{
        try {
            Properties properties = new Properties();
//            properties.load(new FileInputStream("src\\main\\java\\druid.properties"));
            properties.load(JDBCUtilsByDruid.class.getClassLoader()
                    .getResourceAsStream("druid.properties"));
            dataSource = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

//    public static Connection getConnection(){
//        try {
//            return connection = dataSource.getConnection();
//        } catch (SQLException e) {
//            throw new RuntimeException(e);
//        }
//    }

    public static Connection getConnection(){
        Connection conn = threadLocal.get();
        if(conn == null){
            try {
                conn = dataSource.getConnection();
                conn.setAutoCommit(false);
                threadLocal.set(conn);
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        return conn;
    }

    public static void commit(){
        Connection conn = threadLocal.get();
        if(conn != null){
            try {
                conn.commit();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            } finally {
                try {
                    conn.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
        }
        threadLocal.remove();
    }

    public static void rollback(){
        Connection connection = threadLocal.get();
        if(connection != null){
            try {
                connection.rollback();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            } finally {
                try {
                    connection.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
        }
        threadLocal.remove();
    }


    public static void close(ResultSet resultSet, Statement statement, Connection connection){
        try {
            if(resultSet != null)
                resultSet.close();
            if(statement != null)
                statement.close();
            if(connection != null)
                connection.close();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }

}
